<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { computed } from 'vue'
import { cloneDeep } from 'lodash-es'
import { defaultFormData, formRules } from '../index'
import { PAGING } from '@/constant'

const props = defineProps<{
  selectOptions?: any[]
}>()
const emits = defineEmits<{
  keyChange: []
}>()
// ------------------use------------------
// #region
const { $message } = useCurrentInstance()
const [defaultOptions, setDefaultOptions] = useState<any[]>(
  [],
)
const [isChange, setIsChange] = useState(false)
const [formData, setFormData] = useState({
  ...defaultFormData,
})
// #endregion
// ------------------静态变量------------------
// #region
const defaultTime = new Date(
  formatTime(Date.now(), 'YYYY-MM-DD 00:00:00'),
)
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const formRef = ref<FormInstance | null>(null)
// #endregion
// ------------------reactive------
// #region
// #endregion
// ------------------computed------
// #region
const options = computed(() => {
  if (
    !props.selectOptions
    || props.selectOptions?.length === 0
  ) {
    return defaultOptions.value.filter(
      item => item.dicKey !== '0m',
    )
  }
  return props.selectOptions.filter(
    item => item.dicKey !== '0m',
  )
})
const computedTime = computed({
  get() {
    return [
      formData.value.startTime,
      formData.value.endTime,
    ]
  },
  set([a, b]: any) {
    formData.value.startTime = a
    formData.value.endTime = b
  },
})
const dateType = computed(() => {
  const key = formData.value.key
  if (key === '1H') {
    return 'datetimerange'
  }
  else if (key === '1d') {
    return 'daterange'
  }
  else if (key === '1M') {
    return 'monthrange'
  }
  else {
    return 'year'
  }
})
const dateFormat = computed(() => {
  const key = formData.value.key
  if (key === '1H') {
    return 'YYYY-MM-DD HH:mm'
  }
  else if (key === '1d') {
    return 'YYYY-MM-DD'
  }
  else if (key === '1M') {
    return 'YYYY-MM'
  }
  else {
    return 'YYYY'
  }
})

onMounted(async () => {
  await sleep(300)
  if (
    !props.selectOptions
    || props.selectOptions?.length === 0
  ) {
    getOptions()
  }
})
// #endregion
// ------------------内置方法---------------------
// #region
watch(
  () => formData.value.key,
  async () => {
    setIsChange(true)
    await nextTick()
    setIsChange(false)
  },
)
// #endregion
// ------------------方法---------------------
// #region
async function validate() {
  const { startTime, endTime } = unref(formData)
  const startDate = new Date(startTime)
  const endDate = new Date(endTime)
  // DatePicker组件中无法控制选择未来的日期
  if (endDate.getTime() > Date.now()) {
    ElMessage.error('结束时间不能是未来的时间')
    return false
  }
  if (startDate.getTime() > endDate.getTime()) {
    $message.error('结束时间不能小于开始时间！')
    return false
  }
  return await formRef.value?.validate()
}
async function getOptions() {
  const { data } = await sysDictionaryEncoApi.queryList(
    'SHI_JIAN_KE_LI',
  )
  setDefaultOptions(data)
}
function handleChange() {
  formData.value.startTime = ''
  formData.value.endTime = ''
  emits('keyChange')
}
// #endregion
defineExpose({
  validate,
  reset: () => {
    formRef.value?.resetFields()
    setFormData({ ...defaultFormData })
  },
  getData: () => cloneDeep(unref(formData)),
  test: (data: any) => {
    console.warn(data)

    Object.assign(formData.value, data)
  },
})
</script>

<template>
  <el-form
    ref="formRef"
    label-width="80px"
    label-position="right"
    :model="formData"
    :rules="formRules"
    inline
  >
    <el-form-item
      label="时间类型"
      prop="key"
      class="width-fill"
    >
      <ElSelect
        v-model="formData.key"
        class="width-fill"
        :disabled="options.length === 0"
        @change="handleChange"
      >
        <ElOption
          v-for="option in options"
          :key="option.dicValue"
          :label="option.dicValue"
          :value="option.dicKey"
        />
      </ElSelect>
    </el-form-item>
    <template v-if="formData.key === '1y'">
      <el-form-item
        prop="startTime"
        label="开始时间"
        class="width-fill"
      >
        <el-date-picker
          v-model="formData.startTime"
          type="year"
          value-format="YYYY"
          :disabled="!formData.key"
          :disabled-date="PAGING.handleDisabledDate"
          class="width-fill"
        />
      </el-form-item>
      <el-form-item
        label="结束时间"
        prop="endTime"
        class="width-fill"
      >
        <el-date-picker
          v-model="formData.endTime"
          type="year"
          value-format="YYYY"
          :disabled="!formData.key"
          :disabled-date="PAGING.handleDisabledDate"
          class="width-fill"
        />
      </el-form-item>
    </template>
    <el-form-item
      v-else
      label="重算时间"
      prop="startTime"
      class="width-fill"
    >
      <el-date-picker
        v-if="!isChange"
        v-model="computedTime"
        :type="dateType"
        :value-format="dateFormat"
        :format="dateFormat"
        :disabled="!formData.key"
        :clearable="false"
        unlink-panels
        :disabled-date="PAGING.handleDisabledDate"
        :default-value="defaultTime"
      />
    </el-form-item>
  </el-form>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
